// pages/2411Ayiliao-pages/appointment/record.js
Page({
	data: {
		currentPatient: {
			name: '',
			relationship: '本人',
			idCard: ''
		},
		activeFilter: 'lastYear',
		appointmentList: []
	},

	onLoad() {
		this.loadCurrentPatient()
		this.loadAppointmentList()
	},

	onShow() {
		// 每次显示页面时刷新数据
		this.loadAppointmentList()
	},

	// 加载当前患者信息
	loadCurrentPatient() {
		// 从后端获取默认就诊人信息
		wx.request({
			url: 'http://localhost:8005/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				if (res.statusCode === 200 && res.data) {
					let list = res.data
					if (typeof list === 'string') {
						try { list = JSON.parse(list) } catch (e) { return }
					}
					if (list.code !== undefined) list = list.data
					if (!Array.isArray(list)) return
					
					// 找到默认就诊人
					const defaultPatient = list.find(p => p.isDefault === 1)
					if (defaultPatient) {
						this.setData({
							currentPatient: {
								name: defaultPatient.name,
								relationship: defaultPatient.relationTypeName || '本人',
								idCard: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
							}
						})
					} else {
						// 如果没有默认就诊人，使用第一个就诊人
						const firstPatient = list[0]
						if (firstPatient) {
							this.setData({
								currentPatient: {
									name: firstPatient.name,
									relationship: firstPatient.relationTypeName || '本人',
									idCard: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
								}
							})
						}
					}
				}
			}
		})
	},

	// 加载预约记录列表
	loadAppointmentList() {
		wx.showLoading({
			title: '加载中...'
		})

		wx.request({
			url: 'http://localhost:8082/appointment/list',
			method: 'GET',
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				wx.hideLoading()
				
				if (res.statusCode === 200 && res.data) {
					let appointmentData = res.data
					
					// 处理数据格式
					if (typeof appointmentData === 'string') {
						try {
							appointmentData = JSON.parse(appointmentData)
						} catch (e) {
							this.setMockData()
							return
						}
					}
					
					if (!Array.isArray(appointmentData)) {
						if (appointmentData.data && Array.isArray(appointmentData.data)) {
							appointmentData = appointmentData.data
						} else if (appointmentData.list && Array.isArray(appointmentData.list)) {
							appointmentData = appointmentData.list
						} else {
							this.setMockData()
							return
						}
					}
					
					// 处理预约记录数据
					const processedData = appointmentData.map(item => ({
						id: item.id || item.appointmentId,
						department: item.department || item.deptName || '神经内科门诊',
						doctorName: item.doctorName || item.doctor || '刘美',
						consultationRoom: item.consultationRoom || item.room || '消化内科门诊3楼东区501',
						consultationTime: item.consultationTime || item.appointmentTime || '2020年10月5日 10:50',
						patientName: item.patientName || item.username || '王敏',
						status: item.status || 'success',
						statusText: this.getStatusText(item.status),
						statusClass: this.getStatusClass(item.status)
					}))
					
					this.setData({
						appointmentList: processedData
					})
				} else {
					this.setMockData()
				}
			},
			fail: (error) => {
				wx.hideLoading()
				console.error('加载预约记录失败:', error)
				this.setMockData()
			}
		})
	},

	// 设置模拟数据
	setMockData() {
		const mockData = [
			{
				id: 1,
				department: '神经内科门诊',
				doctorName: '刘美',
				consultationRoom: '消化内科门诊3楼东区501',
				consultationTime: '2020年10月5日 10:50',
				patientName: '王敏',
				status: 'success',
				statusText: '预约成功',
				statusClass: 'success'
			},
			{
				id: 2,
				department: '神经内科门诊',
				doctorName: '刘美',
				consultationRoom: '消化内科门诊3楼东区501',
				consultationTime: '2020年9月15日 14:30',
				patientName: '王敏',
				status: 'completed',
				statusText: '已完成',
				statusClass: 'completed'
			},
			{
				id: 3,
				department: '神经内科门诊',
				doctorName: '刘美',
				consultationRoom: '消化内科门诊3楼东区501',
				consultationTime: '2020年8月20日 09:00',
				patientName: '王敏',
				status: 'cancelled',
				statusText: '已取消',
				statusClass: 'cancelled'
			}
		]
		
		this.setData({
			appointmentList: mockData
		})
	},

	// 获取状态文本
	getStatusText(status) {
		const statusMap = {
			'success': '预约成功',
			'completed': '已完成',
			'cancelled': '已取消',
			'pending': '待就诊'
		}
		return statusMap[status] || '未知状态'
	},

	// 获取状态样式类
	getStatusClass(status) {
		const classMap = {
			'success': 'success',
			'completed': 'completed',
			'cancelled': 'cancelled',
			'pending': 'pending'
		}
		return classMap[status] || 'default'
	},

	// 切换就诊人
	switchPatient() {
		// 先加载患者列表
		this.loadPatientList()
	},
	
	// 加载患者列表
	loadPatientList() {
		wx.showLoading({ title: '加载中...' })
		wx.request({
			url: 'http://localhost:8080/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				wx.hideLoading()
				if (res.statusCode === 200 && res.data) {
					let patientData = res.data
					
					// 处理数据格式
					if (typeof patientData === 'string') {
						try {
							patientData = JSON.parse(patientData)
						} catch (e) {
							console.error('JSON解析失败:', e)
							return
						}
					}
					
					// 处理Result包装的数据
					if (patientData.code !== undefined) {
						if (patientData.code !== 200) {
							console.error('后端返回错误:', patientData.message)
							wx.showToast({
								title: patientData.message || '请求失败',
								icon: 'none'
							})
							return
						}
						patientData = patientData.data
					}
					
					// 提取患者数组
					if (!Array.isArray(patientData)) {
						if (patientData.data && Array.isArray(patientData.data)) {
							patientData = patientData.data
						} else if (patientData.list && Array.isArray(patientData.list)) {
							patientData = patientData.list
						} else if (patientData.patients && Array.isArray(patientData.patients)) {
							patientData = patientData.patients
						} else {
							console.error('数据不是数组格式:', patientData)
							return
						}
					}
					
					// 构建选择列表
					const itemList = patientData.map(patient => 
						`${patient.name || patient.patientName} (${patient.relationTypeName || patient.relationship || '本人'})`
					)
					
					wx.showActionSheet({
						itemList: itemList,
						success: (res) => {
							if (res.tapIndex >= 0 && res.tapIndex < patientData.length) {
								const selectedPatient = patientData[res.tapIndex]
								const patientInfo = {
									name: selectedPatient.name || selectedPatient.patientName,
									relationship: selectedPatient.relationTypeName || selectedPatient.relationship || '本人',
									idCard: selectedPatient.idCardNumber || selectedPatient.idCard || '622*********0909'
								}
								
								this.setData({
									currentPatient: patientInfo
								})
								
								// 重新加载该患者的预约记录
								this.loadAppointmentList()
								
								wx.showToast({
									title: '已切换到' + patientInfo.name,
									icon: 'success'
								})
							}
						}
					})
				} else {
					wx.showToast({
						title: '加载患者列表失败',
						icon: 'none'
					})
				}
			},
			fail: (error) => {
				wx.hideLoading()
				console.error('网络请求失败:', error)
				wx.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			}
		})
	},

	// 选择筛选条件
	selectFilter(e) {
		const filter = e.currentTarget.dataset.filter
		this.setData({
			activeFilter: filter
		})
		this.loadAppointmentList()
	},

	// 查看详情
	viewDetail(e) {
		const item = e.currentTarget.dataset.item
		wx.navigateTo({
			url: `/pages/2411Ayiliao-pages/appointment/detail?id=${item.id}&status=${item.status}`
		})
	},

}) 